import { Message, MessageType, MessageDirection } from "@/types/chat";
import React, { Fragment, useEffect, useState } from "react";
import { useLocation, useParams } from 'react-router-dom';
import styles from "./dialog-message.module.scss";
import { DialogMessageItem } from "@/app/components/dialog/dialog-message-item";
import { MessageRole } from "@/types/chat";
import { DialogMessageInput } from "@/app/components/dialog/dialog-message-input";
import { createNewMessage, userChatStore } from "@/app/store/chat-store";
import userScrollToBottom from '@/app/hooks/useScrollToBottom';



interface Props {
    id: string,
    title: string
}

/**
 * 聊天面板
 * @constructor
 */
export function DialogMessage() {
    const { id } = useParams();
    const chatStore = userChatStore();
    const currentSession = chatStore.currentSession();
    const location = useLocation();
    const { scrollRef, setAutoScroll, scrollToBottom } = userScrollToBottom();
    const title = location.state?.title || "新的对话";

    // TODO 测试
    // 本组件维护 messages为 useState的messages, 需要从chat-state中获取当前session的messages
    const [messages, setMessages] = useState<Message[]>([]);
    const fetchDetail = async () => {
        const session = await chatStore.currentSession()    // 返回一个 chatSession[]
        const messages = session?.messages
        setMessages(messages)
    }
    // 切换到不同Chat-Item (动态路由切换)
    useEffect(() => {
        fetchDetail().then(r => {
        });
    }, [id]);


    // 输入事件
    const onEnter = async (value: string) => {
        // 创建用户新消息
        const newMessage = createNewMessage(value, MessageRole.user)
        setMessages([...messages, newMessage])
        // OpenAI 回复
        await chatStore.onSendMessage(newMessage)
        //Test 回显用户消息
        await fetchDetail()
    }


    const clearContextIndex =
        (currentSession.clearContextIndex ?? -1) >= 0
            ? currentSession.clearContextIndex!
            : -1;
    const markdownContent = `## test测试文本`

    return (

        // TODO 开发完成
        // <div className={styles.wrapper}>
        //     <div className={styles.header}>{title}</div>
        //     <div className={styles.scroll} ref={scrollRef}>
        //         {currentSession.messages?.map(
        //             (message, index) => {
        //                 const shouldShowClearContextDivider = index === clearContextIndex - 1;
        //                 return <>
        //                     <DialogMessageItem message={message} key={index} parentRef={scrollRef}/>
        //                     {shouldShowClearContextDivider && <ClearContextDivider/>}
        //                 </>
        //             })
        //         }
        //     </div>
        //     <DialogMessageInput onEnter={onEnter} />
        // </div>

        <div className={styles.wrapper}>
            <div className={styles.header}>{title}</div>
            <div className={styles.scroll} ref={scrollRef}>
                {messages.map(
                    (message, index) => {
                        const shouldShowClearContextDivider = index === clearContextIndex - 1;
                        // return <>
                        //     <DialogMessageItem message={message} key={message.id} parentRef={scrollRef}/>
                        //     {shouldShowClearContextDivider && <ClearContextDivider key={index}/>}
                        // </>
                        return <Fragment key={index}>
                            <DialogMessageItem message={message} parentRef={scrollRef} />
                            {shouldShowClearContextDivider && <ClearContextDivider key={index} />}
                        </Fragment>
                    })
                }
            </div>
            
            <DialogMessageInput onEnter={onEnter} />
        </div>
    );

}

/**
 * 清除上下文对话信息
 * @constructor
 */
function ClearContextDivider() {
    const chatStore = userChatStore();

    return (
        <div
            className={styles["clear-context"]}
            onClick={() =>
                chatStore.updateCurrentSession(
                    (session) => (session.clearContextIndex = undefined),
                )
            }
        >
            <div className={styles["clear-context-tips"]}>上下文已清除</div>
        </div>
    );
}